package com.treetao.union.core.tencent.sms;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.treetao.union.core.exception.DevMException;
import com.treetao.union.core.util.HttpKit;
import com.treetao.union.core.util.RandomUtils;
import com.treetao.union.core.util.hex.SHA256Util;

import lombok.extern.slf4j.Slf4j;

/**
 * 腾讯发短信工具
 * 
 * @author Dev.M
 *
 */
@Slf4j
@Component
public class TencentSmsService {
	
	private static Map<String,TencentSmsOption> selfs = new HashMap<>();

	public void config(String sno,TencentSmsOption option) {
		check(option);
		boolean refresh = option.isRefresh();
		if(!selfs.containsKey(sno) || refresh) {
			selfs.put(sno, option);
		} 
	}

	public boolean sendSms(String sno,String mobile, ArrayList<String> params) {
		TencentSmsOption option = selfs.get(sno);
		check(option);
		String random = RandomUtils.randomString(32);
		long time = System.currentTimeMillis() / 1000;
		String url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms?sdkappid=%s&random=%s";
		String uri = String.format(url, option.getAppid(), random);

		Map<String, Object> data = new HashMap<>();
		data.put("ext", "");
		data.put("extend", "");
		data.put("params", params);

		String hexStr = "appkey=%s&random=%s&time=%s&mobile=%s";
		String sig = SHA256Util.getSHA256StrJava(String.format(hexStr, option.getAppkey(), random, time, mobile));
		data.put("sig", sig);
		data.put("sign", option.getSign());

		Map<String, String> telMap = new HashMap<>();
		telMap.put("nationcode", "86");
		telMap.put("mobile", mobile);
		data.put("tel", telMap);
		data.put("time", time);
		data.put("tpl_id", option.getTpl_id());

		String requestBody = JSONObject.toJSONString(data);
		log.info("TencentSms请求BODY：\n");
		log.info(requestBody);

		String result = HttpKit.post(uri, null, requestBody);
		log.info("\n====TencentSms返回结果：\n");
		log.info(result);

		try {
			org.json.JSONObject obj = new org.json.JSONObject(result);
			if (!obj.has("result") || obj.getInt("result") != 0) {
				throw new DevMException("短信发送失败");
			}
			return true;
		} catch (JSONException e) {
			log.error(e.getMessage());
			throw new DevMException("短信发送失败!");
		}
	}
	
	public static void check(TencentSmsOption option) {
		if(StringUtils.isEmpty(option.getAppid())) {
			throw new DevMException("option required");
		}
		if(StringUtils.isEmpty(option.getAppid())) {
			throw new DevMException("appid cannot be empty");
		}
		if(StringUtils.isEmpty(option.getAppkey())) {
			throw new DevMException("appkey cannot be empty");
		}
		if(StringUtils.isEmpty(option.getSign())) {
			throw new DevMException("sign cannot be empty");
		}
		if(StringUtils.isEmpty(option.getTpl_id())) {
			throw new DevMException("tlp_id cannot be empty");
		}
	}
}
